export const showSelectedObjectKeys = (
  originalObject: object,
  keysToShow: string[]
): object => {
  const filteredObject = {};
  Object.keys(originalObject).forEach((key) => {
    if (keysToShow.includes(key)) filteredObject[key] = originalObject[key];
  });
  return filteredObject;
};

export const hideObjectKeysWithoutValues = (
  originalObject: object
): object => {
  const filteredObject = {};
  Object.keys(originalObject).forEach((key) => {
    if (originalObject[key] !== undefined) filteredObject[key] = originalObject[key];
  });
  return filteredObject;
};

export const hideSelectedObjectKeys = (
  originalObject: object,
  keysToHide: string[]
): object => {
  const filteredObject = {};
  Object.keys(originalObject).forEach((key) => {
    if (!keysToHide.includes(key)) filteredObject[key] = originalObject[key];
  });
  return filteredObject;
};

export const dateToTimestampWithTimezone = (date: Date): number => {
  // 将带时区的日期转换为ISO字符串
  const isoString = date.toISOString();
  // 将ISO字符串转换为时间戳
  return Date.parse(isoString);
}

export function removeEmpty(obj: any): any {
  if (obj === null || obj === undefined) return obj;

  if (typeof obj !== 'object') return obj;

  if (Array.isArray(obj)) {
    return obj
      .map(removeEmpty)
      .filter((item) => item !== null && item !== undefined);
  }

  return Object.entries(obj)
    .map(([key, value], index) => ({ [key]: removeEmpty(value) }))
    .filter(
      (item) =>
        Object.values(item)[0] !== null && Object.values(item)[0] !== undefined,
    )
    .reduce((acc, curr) => ({ ...acc, ...curr }), {});
}

export function filterTreeData(data, idsToKeep): [] {
  return data
    .filter(item => idsToKeep.includes(item.id)) // 过滤顶级节点
    .map(item => ({
      ...item,
      children: filterTreeData(item.children, idsToKeep) // 递归过滤子节点
    }));
}

/**
 * 处理ID值的类型转换
 * @param {any} id 输入的ID值
 * @param {string} idType 数据库中的ID字段类型
 * @returns {any} 转换后的ID值
 */
export function processIdValue(id, idType = 'text') {
  // 对于整数类型的ID字段，进行类型转换
  if (['integer', 'int', 'bigint', 'smallint'].includes(idType.toLowerCase())) {
    const parsedId = parseInt(id, 10);
    if (isNaN(parsedId)) {
      throw new Error(`Invalid ID value: ${id} must be a number`);
    }
    return parsedId;
  }
  // 对于其他类型，保持原样
  return id;
}

/**
 * 处理ID数组的类型转换
 * @param {Array} ids 输入的ID数组
 * @param {string} idType 数据库中的ID字段类型
 * @returns {Array} 转换后的ID数组
 */
export function processIdArray(ids, idType = 'text') {
  return ids.map(id => processIdValue(id, idType));
}

// 从DATABASE_URL解析配置
export const parseDbUrl = (url: string) => {
  const dbUrl = new URL(url)
  return {
    user: dbUrl.username,
    password: dbUrl.password,
    host: dbUrl.hostname,
    port: dbUrl.port,
    database: dbUrl.pathname.slice(1),
    protocol: dbUrl.protocol.slice(0, -1), // 去掉最后的冒号
  }
}